from threading import Thread, Condition, currentThread
import threading
import time


class Goods:

    def __init__(self):
        self.count = 0

    def produce(self):
        self.count += 1

    def consumer(self):
        if self.count > 0:
            print("消费者消费了一个产品")
            self.count -= 1

    def isEmpty(self):
        return not self.count


class Producer(Thread):

    def __init__(self, con, goods):
        Thread.__init__(self)
        self.goods = goods
        self.con = con

    def run(self):
        goods = self.goods
        while 1:
            con.acquire()
            goods.produce()
            print("Goods count:",goods.count, "Producer thread produced",currentThread())
            con.notifyAll()
            con.release()
            time.sleep(3)


class Consumer(Thread):

    def __init__(self, con, goods):
        Thread.__init__(self)
        self.goods = goods
        self.con = con

    def run(self):
        goods = self.goods
        while 1:
            con.acquire()
            if goods.isEmpty():
                con.wait()
            goods.consumer()
            print("Goods count:", goods.count, "Consumer thread consumered")
            con.release()
            time.sleep(1)


if __name__ == '__main__':
    goods = Goods()
    con = Condition()

    for i in range(2):
        producer = Producer(con, goods)
        producer.start()
    #producer.join()  # 启动生产者

    for i in range(5):
        consumer = Consumer(con, goods)
        consumer.start()
        #consumer.join()

